package xstring

import (
	"fmt"
	"net/url"
	"regexp"
	"strings"
)

// 根据基URL获取当前URL
//
//	base	基础URL
//	target	待跳转URL
func Url(base, target string) string {
	if target == "" {
		return base
	}
	if target[0] == '/' {
		url_path, err := url.Parse(base)
		if err != nil {
			return ""
		}
		if url_path.Scheme == "http" && url_path.Port() == "80" || url_path.Scheme == "https" && url_path.Port() == "443" {
			return fmt.Sprintf("%s://%s%s", url_path.Scheme, url_path.Hostname(), target)
		}
		return fmt.Sprintf("%s://%s:%s%s", url_path.Scheme, url_path.Hostname(), url_path.Port(), target)
	} else if strings.Contains(target, "://") {
		return target
	}
	return strings.ReplaceAll(strings.ReplaceAll(base+"/"+target, "//", "/"), ":/", "://")
}

// 提出URL中多余的//，将之替换为单斜线
// PS：若URL中需要多个/，请将参数中的/替换为%2F，避免在此处被替换条
//
//	uri	待替换的URL网址
func UrlFormat(uri string) string {
	inf, err := regexp.Compile(`\/+`)
	if err != nil {
		return uri
	}
	urls := string(inf.ReplaceAll([]byte(uri), []byte("/")))
	return strings.ReplaceAll(urls, ":/", "://")
}
